using UnityEngine;
using UnityEditor;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Settings;
using System.IO;
using System.Collections.Generic;

public class AddAssetsToAddressables : EditorWindow
{
    private static string folderPath = "Assets/HotUpdate";  // 要扫描的文件夹路径
    private static string groupName = "RemoteGroup";  // 要添加到的Addressable Group的名称

    public static void ShowWindow()
    {
        GetWindow<AddAssetsToAddressables>("Add Assets to Addressables");
    }

    private void OnGUI()
    {
        GUILayout.Label("Add Assets to Addressables", EditorStyles.boldLabel);

        folderPath = EditorGUILayout.TextField("Folder Path", folderPath);
        groupName = EditorGUILayout.TextField("Group Name", groupName);

        if (GUILayout.Button("Add Assets"))
        {
            AddAssets();
        }
    }  

    public static void AddAssets()
    {
        if (string.IsNullOrEmpty(folderPath) || string.IsNullOrEmpty(groupName))
        {
            Debug.LogError("Folder path and group name cannot be empty.");
            return;
        }

        string[] files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
        List<string> assetPaths = new List<string>();
        
        foreach (string file in files)
        {
            Debug.Log("file: " + file);
            string extension = Path.GetExtension(file).ToLower();
            if (extension != ".cs" && extension != ".meta" && extension != ".asmdef" && extension != ".bytes")  // 过滤掉脚本文件和meta文件
            {
                assetPaths.Add(file);
            }
        }

        AddressableAssetSettings settings = AddressableAssetSettingsDefaultObject.Settings;
        AddressableAssetGroup group = settings.FindGroup(groupName);

        if (group == null)
        {
            group = settings.CreateGroup(groupName, false, false, true, null);
        }

        foreach (string assetPath in assetPaths)
        {
            Debug.Log("assetPath: " + assetPath);
            string relativePath = assetPath;
            AddressableAssetEntry entry = settings.CreateOrMoveEntry(AssetDatabase.AssetPathToGUID(relativePath), group);
            entry.address = Path.GetFileNameWithoutExtension(relativePath);  // 设置地址为文件名
            entry.SetLabel("all", true);
        } 

        AssetDatabase.SaveAssets();
        Debug.Log("Assets added to Addressables.");
    }
}
